<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchEmpNum"
          placeholder="请输入员工编号"
          style="width: 200px"
          class="filter-item"
        />
        <el-button type="primary" icon="el-icon-search" @click="searchByEmpNum">
          搜索
        </el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">
          添加
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="员工编号" prop="empNum" width="100" align="center" />
        <el-table-column label="考勤类型" width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getTypeTag(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时长(小时)" prop="amount" width="100" align="center" />
        <el-table-column label="记录人" prop="attendancePerson" min-width="120" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="员工编号" prop="empNum">
          <el-input v-model="form.empNum" placeholder="请输入员工编号" />
        </el-form-item>
        <el-form-item label="考勤类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择考勤类型">
            <el-option label="出勤" value="出勤" />
            <el-option label="请假" value="请假" />
            <el-option label="迟到" value="迟到" />
            <el-option label="早退" value="早退" />
            <el-option label="加班" value="加班" />
          </el-select>
        </el-form-item>
        <el-form-item label="时长" prop="amount">
          <el-input-number v-model="form.amount" :min="0" :max="24" :precision="2" />
        </el-form-item>
        <el-form-item label="记录人" prop="attendancePerson">
          <el-input v-model="form.attendancePerson" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      searchEmpNum: "",
      dialogVisible: false,
      dialogTitle: "添加考勤记录",
      isEdit: false,
      form: {
        empNum: '',
        type: '',
        amount: 0,
        attendancePerson: ''
      },
      currentRecordId: null,
      loading: false,
      rules: {
        empNum: [
          { required: true, message: '请输入员工编号', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择考勤类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入时长', trigger: 'blur' }
        ],
        attendancePerson: [
          { required: true, message: '请输入记录人', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.$http.get('/api/attendance_records')
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data;  // 直接赋值返回的数据数组
          } else {
            this.$message.error(response.data.msg);
          }
          this.loading = false;
        })
        .catch(error => {
          this.$message.error('获取数据失败：' + error.message);
          this.loading = false;
        });
    },

    // 修改搜索方法
    searchByEmpNum() {
      if (!this.searchEmpNum) {
        this.getList();
        return;
      }
      this.$http.get(`/api/attendance_records/${this.searchEmpNum}`)
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data;
          } else {
            this.$message.error(response.data.msg);
          }
        });
    },

    // 打开添加对话框
    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = "添加考勤记录";
      this.form = {
        empNum: '',
        type: '',
        amount: 0,
        attendancePerson: ''
      };
      this.dialogVisible = true;
    },

    // 打开编辑对话框
    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑考勤记录';
      this.currentRecordId = row.recordId;
      this.form = {
        empNum: row.empNum,
        type: row.type,
        amount: row.amount,
        attendancePerson: row.attendancePerson
      };
      this.dialogVisible = true;
    },

    // 修改提交表单方法
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = {
            empNum: this.form.empNum,
            type: this.form.type,
            amount: this.form.amount,
            attendancePerson: this.form.attendancePerson
          };

          const config = {
            headers: {
              'Content-Type': 'application/json'
            }
          };

          if (this.isEdit) {
            this.$http.put(`/api/attendance_records/${this.currentRecordId}`, data, config)
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('更新成功');
                  this.dialogVisible = false;
                  this.getList();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          } else {
            this.$http.post('/api/attendance_records', data, config)
              .then(response => {
                if (response.data.code === 200) {
                  this.$message.success('添加成功');
                  this.dialogVisible = false;
                  this.getList();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          }
        }
      });
    },

    // 删除记录
    handleDelete(row) {
      this.$confirm('确认删除该考勤记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/attendance_records/${row.recordId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error(response.data.msg);
            }
          });
      }).catch(() => {});
    },

    getTypeTag(type) {
      switch (type) {
        case '出勤': return '';
        case '请假': return 'info';
        case '迟到': return 'warning';
        case '早退': return 'danger';
        case '加班': return 'success';
        default: return '';
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.box-card {
  margin: 0 auto;
  max-width: 1200px;  /* 限制最大宽度 */
}

.filter-container {
  padding-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;  /* 使用gap替代margin */
}

.filter-item {
  margin: 0;  /* 移除原有margin */
}

.el-table {
  margin-top: 15px;
  width: 100% !important;  /* 确保表格宽度100% */
}

/* 适配不同屏幕尺寸 */
@media screen and (max-width: 1400px) {
  .box-card {
    max-width: 1000px;
  }
}

@media screen and (max-width: 1200px) {
  .box-card {
    max-width: 900px;
  }
}
</style>
